//1创建新的axios实例
//2请求拦截器，有token进行头部携带
//3响应拦截器
//4导出一个函数，调用当前axios实例发请求，返回promise
import axios from "axios";
import store from '@/store'
import router from "@/router";
import { def } from "@vue/shared";
//导出基准路径，原因：其他地方有可能也用
export const baseURL = 'http://pcapi-xiaotuxian-front-devtest.itheima.net/';
const instance = axios.create({
    //axios的一些配置
    baseURL,
    timeout:5000
})

instance.interceptors.request.use(config => {
    //拦截的业务逻辑
    //进行请求配置的修改
    //如果本地有token就在头部携带
    //获取用户信息对象
    const {profile} = store.state.user
    //判断是否有token
    if(profile.token){
        config.headers.Authorization = `Bearer ${profile.token}`
    }
    return config
}, err => {
    return Promise.reject(err)
})

instance.interceptors.response.use(res => {
    res.data
}, err => {
    //401
    if(err.response && err.response.status === 401){
        //2清空无用户信息
        store.commit('user/setUser', {})
        //1.跳转到登录页
        const fullPath = encodeURIComponent(router.currentRoute.value.fullPath)
        router.push('/login?redirectUrl=' + fullPath)
        //2.
    }
    return Promise.reject(err)
})

//请求工具函数
const request = (url, method, submitData) => {
    //负责发请求，请求地址，方式，提交数据
    return instance({
        url,
        method,
        //1.如果是get请求用params
        //2.如果是post,data来传summitData
        //3.const a = {name:100} a.name a[10>9?'3':'4']
        //4.[]设置一个动态key,写js表达式
        //5.method参数 get GET 转成小写

        [method.toLowerCase() === 'get' ? 'params' : 'data']:submitData
    })
}
export default request